package com.tongda.core.repository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.tongda.core.common.Constants;
import com.tongda.core.service.DishService;
import com.tongda.core.utils.DBHelper;
import com.tongda.core.vo.Dish;

/**
 * 菜肴dao 用于维护本地菜谱数据
 * 
 * @author Administrator
 */
public class DishDao {
	private String TABLE_NAME = "dish";
	private DBHelper dbHelper;
	private SQLiteDatabase db;
	private Cursor cursor;
	private String[] selectionArgs;
	private static DishDao instance;

	public DishDao(Context context) {
		this.dbHelper = DBHelper.getInstance(context);
	}

	public static synchronized DishDao getInstance(Context context) {
		if (instance == null) {
			instance = new DishDao(context);
		}
		return instance;
	}

	/**
	 * 新增菜谱
	 * 
	 * @param dish
	 */
	public void insert(Dish dish) {
		synchronized (Constants.objectLock) {
			db = dbHelper.openDatabase();
			ContentValues values = new ContentValues();
			values.put("id", dish.getDishesId());
			values.put("categoryId", dish.getCategoryId());
			values.put("price", dish.getPrice() + "");
			values.put("name", dish.getDishesName());
			values.put("dishescode", dish.getDishesCode());
			values.put("salenum", dish.getSaleNum());
			values.put("searchcode", dish.getSearchCode());
			values.put("unitname", dish.getUnitName());
			values.put("isset", dish.getIsSet());
			db.insert(TABLE_NAME, null, values);
			dbHelper.closeDatabase();
		}

	}

	/**
	 * 构建菜谱的数字查询编码
	 * 
	 * @param dish
	 * @return
	 */
	public static Dish buildSearchCode(Dish dish) {
		StringBuffer buff = new StringBuffer();
		String dishesCode = dish.getDishesCode();
		char[] arr = dishesCode.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			char c = arr[i];
			String str = String.valueOf(c).toUpperCase();
			buff.append(DishService.codeMap.get(str));
		}
		dish.setSearchCode(buff.toString());
		return dish;
	}

	
	public void initInsert(List<Dish> dishes) {
		synchronized (Constants.objectLock) {
			db = dbHelper.openDatabase();
			String checkSql = "SELECT name FROM sqlite_master WHERE type='table' and name='"+TABLE_NAME+"'";
			Cursor cursor = db.rawQuery(checkSql, null);
			if (cursor.getCount() > 0) {
				// 调试阶段暂时都清空 因为表结构经常变化
				db.execSQL("drop table IF EXISTS "+TABLE_NAME);
				db.execSQL(dbHelper.DISH_TABLE_CREATE);
			} else {
				db.execSQL(dbHelper.DISH_TABLE_CREATE);
			}
			for(Dish dish:dishes){
				ContentValues values = new ContentValues();
				dish=buildSearchCode(dish);
				values.put("id", dish.getDishesId());
				values.put("categoryId", dish.getCategoryId());
				values.put("price", dish.getPrice()+"");
				values.put("name", dish.getDishesName());
				values.put("dishescode", dish.getDishesCode());
				values.put("salenum", dish.getSaleNum());
				values.put("searchcode", dish.getSearchCode());
				values.put("unitname", dish.getUnitName());
				values.put("isset", dish.getIsSet());
				db.insert(TABLE_NAME, null, values);
			}

			dbHelper.closeDatabase();
		}
		
	}
	public void batchInsert(List<Dish> dishes) {
		synchronized (Constants.objectLock) {
			db = dbHelper.openDatabase();
			for (Dish dish : dishes) {
				ContentValues values = new ContentValues();
				dish = buildSearchCode(dish);
				values.put("id", dish.getDishesId());
				values.put("categoryId", dish.getCategoryId());
				values.put("price", dish.getPrice() + "");
				values.put("name", dish.getDishesName());
				values.put("dishescode", dish.getDishesCode());
				values.put("salenum", dish.getSaleNum());
				values.put("searchcode", dish.getSearchCode());
				values.put("unitname", dish.getUnitName());
				values.put("isset", dish.getIsSet());
				db.insert(TABLE_NAME, null, values);
			}

			dbHelper.closeDatabase();
		}

	}

	public int getCount() {
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery("select * from dish", null);
		return cursor.getCount();
	}

	/**
	 * 根据编码查询菜肴
	 * 
	 * @param dishesCodes
	 * @return
	 */
	/*
	 * public List<Dish> searchByCodes(List<String> dishesCodes){ List<Dish>
	 * dishes = null; StringBuffer buff = new StringBuffer();
	 * buff.append("select * from "+TABLE_NAME); for(int i
	 * =0;i<dishesCodes.size();i++){ if(i==0){
	 * buff.append(" where dishescode like "+dishesCodes.get(i)+"%"); }else{
	 * buff.append(" or dishescode like "+dishesCodes.get(i)+"%"); } }
	 * buff.append(" order by salenum desc"); db =
	 * dbHelper.getReadableDatabase(); Cursor cursor =
	 * db.rawQuery(buff.toString(),null); if(cursor.getCount()>0){ dishes = new
	 * ArrayList<Dish>(); while(cursor.moveToNext()){ String id =
	 * cursor.getString(cursor.getColumnIndex("id")); String name =
	 * cursor.getString(cursor.getColumnIndex("name")); String dishescode =
	 * cursor.getString(cursor.getColumnIndex("dishescode")); String salenum =
	 * cursor.getString(cursor.getColumnIndex("salenum")); String unitname =
	 * cursor.getString(cursor.getColumnIndex("unitname")); Dish dish = new
	 * Dish(); dish.setDishesId(id); dish.setDishesName(name);
	 * dish.setDishesCode(dishescode);
	 * dish.setSaleNum(Integer.valueOf(salenum).intValue());
	 * dish.setUnitName(unitname); dish.setSaleNum(1); dishes.add(dish); } }
	 * return dishes; }
	 */

	/**
	 * 清空当前菜谱
	 */
	public void clearDish() {
		try {
			db = dbHelper.openDatabase();
			String checkSql = "SELECT name FROM sqlite_master WHERE type='table' and name='"+TABLE_NAME+"'";
			Cursor cursor = db.rawQuery(checkSql, null);
			if (cursor.getCount() > 0) {
				// 调试阶段暂时都清空 因为表结构经常变化
				db.execSQL("drop table IF EXISTS "+TABLE_NAME);
				db.execSQL(dbHelper.DISH_TABLE_CREATE);
			} else {
				db.execSQL(dbHelper.DISH_TABLE_CREATE);
			}
//			String sql = "delete from dish;";
//			db.execSQL(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			dbHelper.closeDatabase();
		}
	}

	/**
	 * 根据数字编码查询菜肴
	 * 
	 * @param searchCode
	 * @return
	 */
	public List<Dish> searchBySearchCodes(String searchCode) {
		List<Dish> dishes = null;
		StringBuffer buff = new StringBuffer();
		// buff.append("select * from dish");
		buff.append("select * from dish where 1=1");
		if (!"".equals(searchCode)) {
		}
		buff.append(" and searchcode like ");
		buff.append("'%" + searchCode + "%'");

		buff.append(" order by salenum desc");
		db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(buff.toString(), null);
		if (cursor.getCount() > 0) {
			dishes = new ArrayList<Dish>();
			while (cursor.moveToNext()) {
				String id = cursor.getString(cursor.getColumnIndex("id"));
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String dishescode = cursor.getString(cursor
						.getColumnIndex("dishescode"));
				String searchcode = cursor.getString(cursor
						.getColumnIndex("searchcode"));
				String salenum = cursor.getString(cursor
						.getColumnIndex("salenum"));
				String unitname = cursor.getString(cursor
						.getColumnIndex("unitname"));
				String isSet = cursor.getString(cursor.getColumnIndex("isset"));
				Dish dish = new Dish();
				dish.setDishesId(id);
				dish.setDishesName(name);
				dish.setPrice(new BigDecimal(cursor.getString(cursor
						.getColumnIndex("price"))));
				dish.setDishesCode(dishescode);

				dish.setSearchCode(searchcode);
				dish.setUnitName(unitname);
				dish.setSaleNum(1);
				dish.setIsSet(isSet);
				dishes.add(dish);
			}
		}
		return dishes;
	}

	public ArrayList<Dish> getDishesByParams(Map<String, String> params) {
		ArrayList<Dish> dishList = new ArrayList<Dish>();
		String selection = " 1 = 1 ";
		List<String> selectionArgsList = null;
		if (params != null) {
			selectionArgsList = new ArrayList<String>();
			Set<String> keys = params.keySet();
			for (String key : keys) {
				Object value = params.get(key);
				String operator = "=";
				if (value != null) {
					String[] valueArray = value.toString().split("_");
					if (valueArray.length == 1) {
						selectionArgsList.add(value.toString());
					} else if (valueArray.length == 2) {
						operator = valueArray[0];
						selectionArgsList.add(valueArray[1] + "");
					}
				}
				selection += " and " + key + "  " + operator + "? ";
			}
			selectionArgs = selectionArgsList.toArray(new String[] {});
		}

		try {
			db = dbHelper.getReadableDatabase();
			String groupBy = null;
			String having = null;
			String orderBy = null;
			String limit = null;
			// Cursor cursor = db.rawQuery("select * from " + TABLE_NAME+
			// " where 1 = 1 and type =" , new String[] { String.valueOf(0) });
			if (params != null) {
				cursor = db.query(TABLE_NAME, null, selection, selectionArgs,
						groupBy, having, orderBy, limit);
			} else {
				cursor = db.query(TABLE_NAME, null, null, null, null, null,
						null);
			}

			while (cursor.moveToNext()) {
				Dish dish = new Dish();
				String id = cursor.getString(cursor.getColumnIndex("id"));
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String dishescode = cursor.getString(cursor
						.getColumnIndex("dishescode"));
				String searchcode = cursor.getString(cursor
						.getColumnIndex("searchcode"));
				String salenum = cursor.getString(cursor
						.getColumnIndex("salenum"));
				String unitname = cursor.getString(cursor
						.getColumnIndex("unitname"));
				String isSet = cursor.getString(cursor.getColumnIndex("isset"));
				dish.setDishesId(id);
				dish.setDishesName(name);
				dish.setDishesCode(dishescode);
				dish.setPrice(new BigDecimal(cursor.getString(cursor
						.getColumnIndex("price"))));

				dish.setSearchCode(searchcode);
				dish.setUnitName(unitname);
				dish.setSaleNum(1);
				dish.setIsSet(isSet);
				dishList.add(dish);
			}
			cursor.close();
		} catch (Exception e) {
			Log.e(this.toString(), e.getMessage());
		}
//		dbHelper.closeDatabase();
		return dishList;
	}

}
